package com.atguigu.flink0922.chapter07;

import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/5 11:19
 */
public class Flink05_Window_Aggregate_1 {
    public static void main(String[] args) throws Exception {
        final Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        
        env.setParallelism(2);
        env
            .fromElements(Tuple2.of("hello", 3L), Tuple2.of("atguigu", 4L), Tuple2.of("hello", 5L))
            .keyBy(t -> t.f0)
            .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            .aggregate(new AggregateFunction<Tuple2<String, Long>, Tuple2<Long, Integer>, Tuple2<Long, Double>>() {
                @Override
                public Tuple2<Long, Integer> createAccumulator() {
                    System.out.println("createAccumulator...");
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return Tuple2.of(0L, 0);
                }
            
                @Override
                public Tuple2<Long, Integer> add(Tuple2<String, Long> value, Tuple2<Long, Integer> accumulator) {
                    System.out.println("add...");
                    return Tuple2.of(accumulator.f0 + value.f1, accumulator.f1 + 1);
                }
            
                @Override
                public Tuple2<Long, Double> getResult(Tuple2<Long, Integer> accumulator) {
                    System.out.println("getResult...");
                    return Tuple2.of(accumulator.f0, accumulator.f0 * 1.0 / accumulator.f1);
                }
            
                @Override
                public Tuple2<Long, Integer> merge(Tuple2<Long, Integer> a, Tuple2<Long, Integer> b) {
                    System.out.println("merge...");
                    return null;
                }
            })
            .print();
        
        env.execute();
    }
}
